package com.myx.typhoon.business.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.myx.typhoon.business.domain.Comment;
import com.myx.typhoon.business.domain.CommentExample;
import com.myx.typhoon.business.domain.CommentExample.Criteria;
import com.myx.typhoon.business.domain.User;
import com.myx.typhoon.business.mapper.CommentMapper;
import com.myx.typhoon.business.service.CommentService;
import com.myx.typhoon.sys.service.UserService;
import com.myx.typhoon.web.bussiness.domian.result.RequestPageVo;
import com.myx.typhoon.web.bussiness.domian.result.RequestResultVo;

/**  
 * @author myx
 * @createTime 2016年1月21日 上午10:19:13  
 * 
 */
@Service("commentService")
public class CommentServiceImpl implements CommentService{

	private static final Logger logger = LoggerFactory.getLogger(CommentServiceImpl.class);
	
	@Resource
	private CommentMapper commentMapper;
	
	@Resource
	private UserService userService;
	
	@Override
	public RequestPageVo<Comment> findCommentByArticleId(Long articleId, int start, int pageSize) {
		RequestPageVo<Comment> page = new RequestPageVo<Comment>();
//		CommentExample example = new CommentExample();
//		Criteria criteria = example.createCriteria();
//		criteria.andArticleIdEqualTo(articleId);
		try {
//			int count = commentMapper.countByExample(example);
			int count = commentMapper.findCommentCountByArticleId(articleId);
			if(count > 0) {
//				example.setStartPage(start);
//				example.setPageSize(pageSize);
//				List<Comment> list = commentMapper.selectByExampleWithBLOBs(example);
				List<Comment> list = commentMapper.findCommentsByArticleId(articleId);
//				page.setData(toTree(list));
				page.setData(list);
				page.setRecordsFiltered(count);
				page.setRecordsTotal(count);
			}
		} catch (Exception e) {
			logger.error("findCommentByArticleId",e);
		}
		return page;
	}
	
	/**
	 * 将评论列表转成树形结构
	 * @param list
	 * @return
	 */
	private List<Comment> toTree(List<Comment> list) {
		List<Comment> commentTree = new ArrayList<Comment>();
		Comment node = null;
		Map<Long, Comment> treeMap = new HashMap<Long, Comment>();
		for (Comment c : list) {
			treeMap.put(c.getCommentId(), c);
		}
		for(Map.Entry<Long, Comment> entry : treeMap.entrySet()) {
			Comment pComment = null;
			node = entry.getValue();
			if(node == null) {
				continue;
			}
			pComment = treeMap.get(node.getParentId());
			if(pComment == null) {
				commentTree.add(node);
			}else {
				List<Comment> cComment = pComment.getChildren();
				if(cComment == null) {
					cComment = new ArrayList<Comment>();
				}
				cComment.add(node);
				pComment.setChildren(cComment);
			}
		}
		return commentTree;
	}
	
	
	public int findArticleCommentCount(Long articleId) {
		int count = 0;
		CommentExample example = new CommentExample();
		Criteria criteria = example.createCriteria();
		criteria.andArticleIdEqualTo(articleId);
		try {
			count = commentMapper.countByExample(example);
		} catch (Exception e) {
			logger.error("findArticleCommentCount",e);
		}
		return count;
	}

	@Override
	public RequestResultVo<Comment> saveComment(Comment comment, Long userId) {
		RequestResultVo<Comment> result = new RequestResultVo<Comment>();
		comment.setLastTime(new Date());
		comment.setCreateTime(new Date());
		comment.setUserId(userId);
		int count = 0;
		try {
			//获取父级评论信息
			if(comment.getParentId() != null) {
				Comment pcom = this.findCommentById(comment.getParentId());
				User user = userService.findUserById(pcom.getUserId());
				String content = comment.getContent();
				comment.setContent(content+" //@"+user.getUsername()+": "+pcom.getContent());
			}
			count = commentMapper.insertSelective(comment);
		} catch (Exception e) {
			logger.error("",e);
		}
		if(count <= 0) {
			result.setSuccess(false);
			result.setErrorMessage("系统繁忙，评论失败！");
		}
		return result;
	}

	@Override
	public Comment findCommentById(Long id) {
		try {
			return commentMapper.selectByPrimaryKey(id);
		} catch (Exception e) {
			logger.error("findCommentById",e);
		}
		return null;
	}
}
